package com.ruoyi.crm.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.excel.core.ExcelResult;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.crm.domain.ContactInfo;
import com.ruoyi.crm.domain.CustomerInfo;
import com.ruoyi.crm.domain.Responsible;
import com.ruoyi.crm.domain.LeadInfo;
import com.ruoyi.crm.service.IContactService;
import com.ruoyi.crm.service.IResponsibleService;
import com.ruoyi.crm.service.Impl.CustomerServiceImpl;
import com.ruoyi.crm.service.Impl.LeaderServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 *
 * 客户线索控制层
 * @author  dxy
 *
 */


@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/lead")
public class LeadInfoController extends BaseController {
    private final LeaderServiceImpl leaderService;
    private final CustomerServiceImpl customerService;
    private final IContactService contactService;
    private final IResponsibleService responsibleService;

    /**
     * 查询客户线索
     */
    @SaCheckPermission("lead:leadInfo:list")
    @GetMapping("/list")
    public TableDataInfo<LeadInfo> leadInfoPageList(LeadInfo leadInfo, PageQuery pageQuery){
        TableDataInfo<LeadInfo> list= leaderService.selectLeadPageList(leadInfo,pageQuery);
        list.getRows().forEach(L->{
            if(L.getCustomerId()!=null) {
                CustomerInfo customerInfo = customerService.selectCustomerById(L.getCustomerId());
                if (customerInfo != null) {
                    L.getParams().put("customerName", customerInfo.getCustomerName());
                }
            }

                if(L.getContactId()!=null){
                    ContactInfo contactInfo=contactService.selectContactById(L.getContactId());
                    if(contactInfo!=null){
                        L.getParams().put("contactName",contactInfo.getContactName());
                        L.getParams().put("phone",contactInfo.getPhone());
                        L.getParams().put("landlineNumber",contactInfo.getLandlineNumber());
                        L.getParams().put("email",contactInfo.getEmail());
                    }
                }
                if(L.getResponsiblePersonId()!=null){
                    Responsible responsible=responsibleService.selectResponsibleById(L.getResponsiblePersonId());
                    if(responsible!=null){
                        L.getParams().put("responsiblePersonName",responsible.getResponsiblePersonName());
                    }


                }

        });
        return list;
    }
    /**
     * 根据客户线索ID获取详细信息
     *
     * @param leadId 客户线索ID
     */
    @SaCheckPermission("lead:leadInfo:query")
    @GetMapping(value = "/{leadId}")
    public R<LeadInfo> leadInfo(@PathVariable Long leadId){
        return R.ok(leaderService.selectLeadById(leadId));
    }
    /**
     *新增客户线索
     */
    @SaCheckPermission("lead:leadInfo:add")
    @Log(title = "客户线索",businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody LeadInfo leadInfo) {
        return toAjax(leaderService.insertLeadById(leadInfo));
    }
    /**
     * 修改客户线索
     */
    @SaCheckPermission("lead:leadInfo:edit")
    @Log(title = "客户线索",businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody LeadInfo leadInfo) {
        return toAjax(leaderService.updateLeadById(leadInfo));

    }
    /**
     * 删除客户线索
     */
    @SaCheckPermission("lead:leadInfo:remove")
    @Log(title = "客户线索",businessType = BusinessType.DELETE)
    @DeleteMapping("/{leadId}")
    public R<Void> remove(@PathVariable Long leadId) {
        return toAjax(leaderService.deleteLeadById(leadId));
    }
    /**
     * 导出客户线索
     */
    @SaCheckPermission("lead:leadInfo:export")
    @Log(title = "客户线索",businessType = BusinessType.EXPORT)
    @PostMapping("/export")
   public void export(HttpServletResponse response, LeadInfo leadInfo)
    {
        List<LeadInfo> list=leaderService.selectLeadList(leadInfo);
        List<LeadInfo> listVo= BeanUtil.copyToList(list,LeadInfo.class);
        ExcelUtil.exportExcel(list, "客户线索数据",LeadInfo.class, response);

    }
    /**
     * 导入客户线索
     */
    @SaCheckPermission("lead:leadInfo:export")
    @Log(title = "客户线索",businessType = BusinessType.IMPORT)
    @PostMapping(value = "/import",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        // 导入方法
        ExcelResult<LeadInfo> result = ExcelUtil.importExcel(file.getInputStream(), LeadInfo.class,false);
        List<LeadInfo> list = result.getList();
        boolean imp=leaderService.insertBatch(list);
        if(!imp){
            return R.fail("导入失败，保存数据库时出错");
        }
        return R.ok(result.getAnalysis());
    }


}
